import AsyncStorage from '@react-native-async-storage/async-storage';
import { STORAGE_KEYS } from '../../utils/constants';

/**
 * 存储服务 - 封装 AsyncStorage 操作
 */
class StorageService {
  /**
   * 保存数据
   */
  async save(key, data) {
    try {
      const jsonData = JSON.stringify(data);
      await AsyncStorage.setItem(key, jsonData);
      return { success: true };
    } catch (error) {
      console.error('Storage save error:', error);
      return { success: false, error: error.message };
    }
  }

  /**
   * 读取数据
   */
  async load(key) {
    try {
      const jsonData = await AsyncStorage.getItem(key);
      if (jsonData === null) {
        return { success: true, data: null };
      }
      const data = JSON.parse(jsonData);
      return { success: true, data };
    } catch (error) {
      console.error('Storage load error:', error);
      return { success: false, error: error.message, data: null };
    }
  }

  /**
   * 删除数据
   */
  async remove(key) {
    try {
      await AsyncStorage.removeItem(key);
      return { success: true };
    } catch (error) {
      console.error('Storage remove error:', error);
      return { success: false, error: error.message };
    }
  }

  /**
   * 清空所有数据
   */
  async clear() {
    try {
      await AsyncStorage.clear();
      return { success: true };
    } catch (error) {
      console.error('Storage clear error:', error);
      return { success: false, error: error.message };
    }
  }

  /**
   * 获取所有键
   */
  async getAllKeys() {
    try {
      const keys = await AsyncStorage.getAllKeys();
      return { success: true, keys };
    } catch (error) {
      console.error('Storage getAllKeys error:', error);
      return { success: false, error: error.message, keys: [] };
    }
  }

  // 计划相关方法
  async savePlans(plans) {
    return this.save(STORAGE_KEYS.PLANS, plans);
  }

  async loadPlans() {
    return this.load(STORAGE_KEYS.PLANS);
  }

  async saveWeeklyPlans(weeklyPlans) {
    return this.save(STORAGE_KEYS.WEEKLY_PLANS, weeklyPlans);
  }

  async loadWeeklyPlans() {
    return this.load(STORAGE_KEYS.WEEKLY_PLANS);
  }

  async saveMonthlyPlans(monthlyPlans) {
    return this.save(STORAGE_KEYS.MONTHLY_PLANS, monthlyPlans);
  }

  async loadMonthlyPlans() {
    return this.load(STORAGE_KEYS.MONTHLY_PLANS);
  }

  async saveSettings(settings) {
    return this.save(STORAGE_KEYS.SETTINGS, settings);
  }

  async loadSettings() {
    return this.load(STORAGE_KEYS.SETTINGS);
  }

  async saveStatistics(statistics) {
    return this.save(STORAGE_KEYS.STATISTICS, statistics);
  }

  async loadStatistics() {
    return this.load(STORAGE_KEYS.STATISTICS);
  }
}

export default new StorageService();

